package com.youmu.shop.login.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.youmu.shop.context.utils.UserContext;
import com.youmu.shop.system.bean.Admin;
import com.youmu.shop.system.vo.UserInfo;

/**
 * 
 * <p>Title:LoginInterceptor</p>
 * @author xc
 * @version	v1.0
 * <p>Date:2016年11月24日上午10:04:17</p>
 * <p>Description:TODO</p>
 */
public class LoginInterceptor implements HandlerInterceptor{
    
	public static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
	    
		UserInfo userInfo = UserContext.getUserInfo();
		Admin admin = UserContext.getAdminInfo();
		
		if(userInfo == null) {
		    userInfo = new UserInfo();
		    ((UserInfo)userInfo).setId(2678);
		    ((UserInfo)userInfo).setUsername("o_ttZwNGZq3QpFtgZ953cmH3sGa0");
	        UserContext.setUserInfo((UserInfo)userInfo);
		}
		
		if(admin == null) {
		    admin = new Admin();
		    admin.setId(20L);
		    admin.setUsername("o_ttZwOeQbMn-h4PkRwk454EAQtU");
		    UserContext.setAdminInfo(admin);
		}
		
		logger.info("login interceptor .... {}, now user {}. ",request.getRequestURL() , userInfo);
		logger.info("login interceptor .... {}, now admin {}. ",request.getRequestURL() , admin);
		if(userInfo == null && admin == null){
		     request.getRequestDispatcher("/dispatching/no-permission.html").forward(request, response);
		     return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}
	
}
